module Main where

import XI.Directory.WS.Xmlable(WsParams (..))
import XI.Directory.GetXiObj
import Codec.Binary.Base64.String
import Data.Maybe
import Data.Time.LocalTime
import Data.List
import XI.Directory.Types
import XI.Directory.Todo
import XI.Directory.Parser
import Control.Concurrent
import Control.Applicative
import Control.Arrow
import Data.Traversable
import XI.Directory.WS.Main (wsProxy, saveProxy) 
import Text.Dot
import Text.PrettyPrint
import HixayGraph
--import System.Vacuum.Cairo
--import Data.Graph.Inductive.Graph

{-
    You should use file TestWSDL.par with following description of params:
    
#	
# if string starts with '#' it is ignored
#
Maybe proxy-file 
host:port
user:pwd
Maybe log-file
#
#
    
-}
check_par par 
    | length par < 4 	= error "TestWSDL.par is incorrect"
    | otherwise 		= par

wsp = do
    par <- readFile "TestWSDL.par" >>= return . check_par . filter ((/="#") . take 1) . lines 
    prxFile <- return . read $ par!!0
    proxy <- wsProxy prxFile >>= newMVar
    log <- newMVar ()
    return WsParams {
            wspProxyMVar = proxy,
            wspLogMVar = log,
            wspServer = par!!1,
            wspAuthorization = Just $ "Basic " ++ (encode $ par!!2),
            wspProxy = prxFile,
            wspProtocolStr = "HTTPBasicAuth?style=document",
            wspLog = read $ par!!3
        }

get_res :: IO [XIObj]		
get_res = do
    wsp' <- wsp
    res <- sequenceA (zipWith (setVar wsp') [getCC, getSA, getRA, getRD, getID, getCS, getIP] ["CC", "SA", "RA", "RD", "ID", "CS", "IP"]) >>= 
            traverse takeMVar >>= return . concat
    saveProxy wsp'
    return res
    where
        setVar wsp' f s = newEmptyMVar >>= (\res -> forkIO (f wsp' >>= (\x -> putMVar res x >> write''' (s ++ "Obj.res") x )) >> return res)
        write' file str = putTime writeFile >> appendFile file (str ++ "\n") >> putTime appendFile
            where 
                putTime f = getZonedTime >>= f file . (++"\n") . show
        write'' s f dl = write' s $ unlines $ map show $ nub $ concatMap maybeToList $ map f dl
        write''' s = write' s . unlines . map show . nub
        
getScenarioChains :: Configuration -> String -> [Chain]
getScenarioChains cfg name = scenario_chains . (!!0) . filter ((==name) . fromMaybe "" . scenario_name) $ (fst cfg)

main :: IO ()
main = do
    res <- get_res
    case scenarios res of 
        Left err -> putStr err
        Right scs -> do 
            writeFile "script.res" $ unlines $ scriptDir scs
            writeFile "script_everything.dot" $ dotChainsString allchains
            writeFile "script_scenario.dot" $ dotChainsString sc_chains
            where 
                sc_chains = getScenarioChains scs "DEMOPROXY"
                allchains = concatMap scenario_chains (fst scs)

